package demo.java.util.concurrent;

import com.google.common.util.concurrent.ThreadFactoryBuilder;

import java.util.concurrent.Executors;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.atomic.AtomicInteger;

public class ThreadFactoryDemo {

    public static void main(String[] args) {
        ThreadFactory threadFactory = Executors.defaultThreadFactory();

    }


    /**
     * guava 或自行封装的ThreadFactory
     *
     * @param nameFormat
     * @param daemon
     * @param handler
     * @return
     */
    public static ThreadFactory guavaThreadFactory(String nameFormat, boolean daemon, Thread.UncaughtExceptionHandler handler) {
        ThreadFactory threadFactory = new ThreadFactoryBuilder()
                .setNameFormat(nameFormat + "-%d")
                .setDaemon(daemon)
                .setUncaughtExceptionHandler(handler)
                .build();
        return threadFactory;
    }


    /**
     * 需要指定线程异常处理器的线程工厂
     */
    public static class SpecialThreadFactory implements ThreadFactory {

        private Thread.UncaughtExceptionHandler handler;

        public SpecialThreadFactory(Thread.UncaughtExceptionHandler handler) {
            super();
            this.handler = handler;
        }

        @Override
        public Thread newThread(Runnable r) {
            Thread t = new Thread(r);
            t.setUncaughtExceptionHandler(handler);
            return t;
        }

    }

    /**
     * 命名线程工厂
     */
    public static class NamedThreadFactory implements ThreadFactory {
        private static final AtomicInteger poolNumber = new AtomicInteger(1);
        private final AtomicInteger threadNumber = new AtomicInteger(1);
        private final String namePrefix;
        private final boolean daemon;

        public NamedThreadFactory(String name, boolean daemon) {
            if (null == name || name.isEmpty()) {
                name = "pool";
            }

            namePrefix = name + "-" + poolNumber.getAndIncrement() + "-thread-";
            this.daemon = daemon;
        }

        public NamedThreadFactory(String name) {
            this(name, false);
        }

        @Override
        public Thread newThread(Runnable r) {
            Thread t = new Thread( r, namePrefix + threadNumber.getAndIncrement());
            t.setDaemon(daemon);
            if (t.getPriority() != Thread.NORM_PRIORITY) {
                t.setPriority(Thread.NORM_PRIORITY);
            }
            return t;
        }
    }

    public static class SimpleThreadFactory implements ThreadFactory {

        @Override
        public Thread newThread(Runnable r) {
            return new Thread(r);
        }
    }

}
